import querystring from 'querystring'
import handleBlogRouter from './src/router/blog.js'
import handleUserRouter from './src/router/user.js'
import { get, set } from './src/db/redis.js'
import { handleHtmlRouter } from './src/router/html.js'
import { access } from './src/utils/log.js'

// const SESSION_DATA = {}

// 用于处理 post data
const getPostData = (req) => {
	return new Promise((resolve, reject) => {
		if (req.method !== 'POST') {
			resolve({})
			return
		}

		if (req.headers['content-type'] !== 'application/json') {
			resolve({})
			return
		}

		let postData = ''
		req.on('data', (chunk) => {
			postData += chunk.toString()
		})

		req.on('end', (err) => {
			if (err) {
				reject(err)
				return
			}

			if (!postData) {
				resolve({})
				return
			}

			resolve(JSON.parse(postData))
		})
	})
}

// 获取 cookie 的过期时间
const getCookieExpires = () => {
	const d = new Date()
	d.setTime(d.getTime() + 24 * 60 * 60 * 1000)
	return d.toGMTString()
}

const serverHandle = async (req, res) => {
	// 记录 access log
	access(
		`${req.method} -- ${req.url} -- ${
			req.headers['user-agent']
		} -- ${Date.now()}`
	)
	// 获取 path
	const url = req.url
	req.path = url.split('?')[0]

	// 解析 query
	req.query = querystring.parse(url.split('?')[1])

	//解析 cookie
	req.cookie = {}
	const cookieStr = req.headers.cookie || ''
	cookieStr.split(';').forEach((item) => {
		if (!item) {
			return
		}
		const [key, value] = item.split('=')
		req.cookie[key.trim()] = value.trim()
	})

	// 解析 session
	/* let needSetCookie = false
	let userId = req.cookie.userid
	if (userId) {
		if (!SESSION_DATA[userId]) {
			SESSION_DATA[userId] = {}
		}
	} else {
		needSetCookie = true
		userId = `${Date.now()}_${Math.random()}`
		SESSION_DATA[userId] = {}
	}
	req.session = SESSION_DATA[userId] */

	// 解析 session (使用 redis)
	let needSetCookie = false
	let userId = req.cookie.userid
	if (!userId) {
		needSetCookie = true
		userId = `${Date.now()}_${Math.random()}`
		// 初始化 redis 中的 session 值
		set(userId, {})
	}
	// 获取 session
	req.sessionId = userId
	const sessionData = await get(req.sessionId)
	if (sessionData === null) {
		// 初始化 redis 中的 session 值
		set(req.sessionId, {})
		// 设置 session
		req.session = {}
	} else {
		req.session = sessionData
	}

	// 处理 postData
	const postData = await getPostData(req)
	req.body = postData

	// 处理 blog 路由
	const blogData = await handleBlogRouter(req, res)
	if (blogData) {
		if (needSetCookie) {
			res.setHeader(
				'Set-Cookie',
				`userid=${userId};path=/;httpOnly;expires=${getCookieExpires()}`
			)
		}
		return res.end(JSON.stringify(blogData))
	}

	// 处理 user 路由
	const userData = await handleUserRouter(req, res)
	if (userData) {
		if (needSetCookie) {
			res.setHeader(
				'Set-Cookie',
				`userid=${userId};path=/;httpOnly;expires=${getCookieExpires()}`
			)
		}
		return res.end(JSON.stringify(userData))
	}

	// 处理 html 路由
	const html = await handleHtmlRouter(req, res)
	if (html) {
		return res.end(html)
	}

	// 未命中路由, 返回 404
	res.writeHead(404, { 'content-type': 'text/plain' })
	res.write('404 Not Found\n')
	res.end()
}

export default serverHandle
